package com.hongxun.design.activitys;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.CreateProjectAttributeCodeSetAdapter;
import com.hongxun.design.bean.BitTypeTabItemBean;
import com.hongxun.design.bean.CodeSetVersionBean;
import com.hongxun.design.bean.MaterialInfoBean;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/5/19.
 */
public class CreateProjectAttributeCodeActivity extends BaseActivity implements HeadSecond, SwipeRefreshLayout.OnRefreshListener {
    //典设相关
    Handler codeSetHandler, materialHandler;
    private final int Successed = 0;
    private final int addList = 1;
    private final int updateList = 2;
    List<CodeSetVersionBean> bean;
    public String typecode = "";
    public String code = MString.click_in;
    public String name = "";

    CreateProjectAttributeCodeSetAdapter adapter;
    SwipeRefreshListView list;
    String title = MString.CreateProjectAttributeCode;

    private Handler projectListHandler;
    public List<ProjectItemBean> data;
    int startNum = 0;
    int addNum = MyApp.addNum;

    String project_name = "";

    String matId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createprojectattributecode);
        findBar();
        findView();
        initialization();
    }

    private void getIntentData() {
        typecode = getIntent().getExtras().getString(MString.TYPE);
        switch (typecode) {
            case MString.projectChoice:
                title = "选择项目";
                break;
            case MString.projectChoice_selfcheck:
                title = "选择项目";
                break;
            case MString.Type_GetPT_ID:
                title = "选择类型";
                break;
            case MString.Type_Material:
                title = "选择型号";
                matId = getIntent().getExtras().getString(MString.CODE);
                break;
            default:
                try {
                    code = getIntent().getExtras().getString(MString.CODE);
                    name = getIntent().getExtras().getString(MString.name);
                } catch (Exception e) {
                }
                break;
        }
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, View.GONE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
    }

    @Override
    protected void onStart() {
        mActivity = this;
        super.onStart();
    }

    @Override
    protected void findView() {
        list = (SwipeRefreshListView) findViewById(R.id.attributecode_list);
        list.setOnRefreshListener(this);
        super.findView();
    }

    @Override
    protected void initialization() {
        switch (typecode) {
            case MString.projectChoice:
                initialization_choiceProject();
                break;
            case MString.projectChoice_selfcheck:
                initialization_choiceProject();
                break;
            case MString.Type_GetPT_ID:
                initialization_choicetype();
                break;
            case MString.Type_Material:
                initialization_choiceMaterial();
                break;
            default:
                addHandler();
                getDataForCodeSet();
                break;
        }
        super.initialization();
    }

    /**
     * 选择项目
     **/
    private void initialization_choiceProject() {
        RelativeLayout choice_item = (RelativeLayout) findViewById(R.id.choice_project_search);
        choice_item.setVisibility(View.VISIBLE);
        EditText serch_words = (EditText) findViewById(R.id.serch_words);
        TextView serch_button = (TextView) findViewById(R.id.serch_button);
        serch_button.setOnClickListener(new MClickListener(0, serch_words) {
            @Override
            public void onClick(View view, int position, Object msg) {
                EditText serch_words = (EditText) msg;
                project_name = serch_words.getText().toString();
                onRefresh();
            }
        });

        addProjectListHandler();
        onRefresh();
    }

    /**
     * 选择点位类型
     **/
    private void initialization_choicetype() {
        List<BitTypeTabItemBean> bit = DataUtil.getBitTypeData(1);
        if (bean == null) {
            bean = new ArrayList<>();
        } else {
            bean.clear();
        }
        for (BitTypeTabItemBean p : bit) {
            CodeSetVersionBean b = new CodeSetVersionBean();
            b.setCodeset_version(p.getName());
            b.setCodeset_version_id(p.getId());
            bean.add(b);
        }

        CodeSetVersionBean all = new CodeSetVersionBean();
        all.setCodeset_version("全部");
        all.setCodeset_version_id("");
        bean.add(all);
        adapter = new CreateProjectAttributeCodeSetAdapter(bean, this);
        list.setAdapter(adapter);
        list.setDivider(1);
    }

    /**
     * 选择材料或模块型号
     **/
    private void initialization_choiceMaterial() {
        addMaterialHandler();
        getlikeNameMaterial();

    }

    private void addMaterialHandler() {
        materialHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        list.setRefreshing(false);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            List<MaterialInfoBean> infoBeans = FastJsonUtil.getMaterialInfoBean((String) msg.obj);
                            if (bean == null) bean = new ArrayList<>();
                            if (infoBeans != null) {
                                if (!infoBeans.isEmpty()) bean.clear();

                                for (MaterialInfoBean p : infoBeans) {
                                    CodeSetVersionBean b = new CodeSetVersionBean();
                                    b.setCodeset_version(p.spec);//spec
                                    b.setCodeset_version_id(p.obj_id + "");//obj_id
                                    bean.add(b);
                                }
                            }
                            materialHandler.sendEmptyMessage(1);
                        } else {
                            list.setRefreshing(false);
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1://加载listview数据
                        if (bean == null) bean = new ArrayList<>();
                        list.setRefreshing(false);
                        if (adapter == null) {
                            adapter = new CreateProjectAttributeCodeSetAdapter(bean, mActivity);
                            list.setAdapter(adapter);
                            list.setFragment(baseActivity);
                            list.setCanScroll(true);
                            list.setDivider(1);
                        } else {
                            list.update();
                            list.removeFooterView();
                        }
                        break;
                    case HttpStringUtil.ADDMROE:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            List<MaterialInfoBean> infoBeans = FastJsonUtil.getMaterialInfoBean((String) msg.obj);
                            if (bean == null) bean = new ArrayList<>();
                            if (infoBeans != null) {
                                for (MaterialInfoBean p : infoBeans) {
                                    CodeSetVersionBean b = new CodeSetVersionBean();
                                    b.setCodeset_version(p.spec);//spec
                                    b.setCodeset_version_id(p.obj_id + "");//obj_id
                                    bean.add(b);
                                }
                            }
                            if (infoBeans == null || infoBeans.isEmpty()) {
                                ToastShow.showShort(mActivity, "没有数据了");
                                list.removeFooterView();
                            } else materialHandler.sendEmptyMessage(1);
                        } else {
                            list.setRefreshing(false);
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        list.setRefreshing(false);
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void getlikeNameMaterial() {
        String versionId = MyApp.currProject.getCodeset_version_id();
        Bundle bundle = getIntent().getExtras();
        if (bundle.containsKey("true")) {//点位材料型号相同的数据
            MyApp.HTTP.getlikeNameMaterial(materialHandler, HttpStringUtil.SUCCESSED, matId, startNum, addNum, versionId);
        } else {//典设材料
            MyApp.HTTP.getlikeNameMaterials(materialHandler, HttpStringUtil.SUCCESSED, matId, startNum, addNum, versionId);
        }
    }


    private void addHandler() {
        codeSetHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (bean == null) {
                                bean = FastJsonUtil.JsonToData_CodeSetVersion((String) msg.obj);
                            } else {
                                bean.clear();
                                bean.addAll(FastJsonUtil.JsonToData_CodeSetVersion((String) msg.obj));
                            }
                            codeSetHandler.sendEmptyMessage(addList);
                        }
                        break;
                    case addList:
                        MyLog.L(MString.SUCCESSED + JSON.toJSONString(bean));
                        if (adapter == null) {
                            adapter = new CreateProjectAttributeCodeSetAdapter(bean, mActivity);
                            list.setAdapter(adapter);
                            list.setDivider(1);
                        } else {
                            list.update();
                            list.setRefreshing(false);
                        }
                        break;
                    case updateList:
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyApp.activity = this;
        mActivity = this;
        baseActivity = this;
    }

    private void getDataForCodeSet() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.getCodeSetVersion(codeSetHandler, HttpStringUtil.SUCCESSED, typecode);
        } else {
            codeSetHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED,
                    ShardPreferencesTool.getshare(this, MString.codeset_type + typecode, "")));
        }

    }

    @Override
    public void onRefresh() {
        switch (typecode) {
            case MString.projectChoice:
                startNum = 0;
                addNum = Integer.MAX_VALUE;
                MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.SUCCESSED, project_name, startNum, startNum + addNum);
                break;
            case MString.projectChoice_selfcheck:
                startNum = 0;
                addNum = MyApp.addNum;
                MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.SUCCESSED, project_name, startNum, startNum + addNum);
                break;
            case MString.Type_GetPT_ID:
                list.setRefreshing(false);
                break;
            case MString.Type_Material:
                startNum = 0;
                addNum = 15;
                getlikeNameMaterial();
                break;
            default:
                getDataForCodeSet();
                break;
        }

    }

    @Override
    public void addMore() {
        super.addMore();
        switch (typecode) {
            case MString.projectChoice:
                if (addNum == Integer.MAX_VALUE) {
                    list.setRefreshing(false);
                    list.removeFooterView();
                    return;
                }
                MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.ADDMROE, project_name, startNum, startNum + addNum);
                break;
            case MString.projectChoice_selfcheck:
                MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.ADDMROE, project_name, startNum, startNum + addNum);
                break;
            case MString.Type_Material:
                startNum = addNum;
                addNum += 15;
                String versionId = MyApp.currProject.getCodeset_version_id().trim();
                Bundle bundle = getIntent().getExtras();
                if (bundle.containsKey("true")) {//点位材料型号相同的数据
                    MyApp.HTTP.getlikeNameMaterial(materialHandler, HttpStringUtil.ADDMROE, matId, startNum, addNum, versionId);
                } else {//典设材料
                    MyApp.HTTP.getlikeNameMaterials(materialHandler, HttpStringUtil.ADDMROE, matId, startNum, addNum, versionId);
                }
                break;
            default:

                break;
        }
    }

    private void addProjectListHandler() {
        projectListHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {

                            setBean((String) msg.obj);
                            // MyApp.File.SaveFileData(MString.File_ProjectList, "{\"projectList\":" + JSON.toJSONString(data) + "}");//存储
                            projectListHandler.sendEmptyMessage(1);
                            startNum = startNum + addNum;
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(data));
                        }
                        break;
                    case 1://加载listview数据
                        MyLog.L(MString.SUCCESSED + JSON.toJSONString(bean));
                        if (bean == null) bean = new ArrayList<>();
                        if (adapter == null) {
                            adapter = new CreateProjectAttributeCodeSetAdapter(bean, mActivity);
                            list.setAdapter(adapter);
                            list.setFragment(baseActivity);
                            list.setCanScroll(true);
                            list.setDivider(1);
                        } else {
                            list.update();
                            list.setRefreshing(false);
                            list.removeFooterView();
                        }
                        break;
                    case HttpStringUtil.ADDMROE:
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;

                }
            }
        };
    }

    private void setBean(String s) {
        if (MString.projectChoice.equals(typecode) || MString.projectChoice_selfcheck.equals(typecode)) {
            if (!MyApp.isOnLine) {
                if (data == null) {
                    data = DataFactory.GetNewProject(FastJsonUtil.JsonToGetProjectListBean(s), GetFileUtil.getProjectStageListFile());
                } else {
                    data.clear();
                    data.addAll(DataFactory.GetNewProject(FastJsonUtil.JsonToGetProjectListBean(s), GetFileUtil.getProjectStageListFile()));
                }
            } else {
                if (data == null) {
                    data = FastJsonUtil.JsonToGetProjectListBean(s);
                } else {
                    data.clear();
                    data.addAll(FastJsonUtil.JsonToGetProjectListBean(s));
                }
            }

        }
        if (data == null) data = new ArrayList<>();
        if (bean == null) {
            bean = new ArrayList<>();
        } else {
            bean.clear();
        }
        if (data != null && data.size() != 0) {
            for (ProjectItemBean p : data) {
                if (MString.projectChoice.equals(typecode)) {
                    if (p.getCurrent_schedule() != null && !DataFactory.checkIsOnlyRead(p)) {
                        CodeSetVersionBean b = new CodeSetVersionBean();
                        b.setCodeset_version(p.getProject_name());
                        bean.add(b);
                    }
                } else {
                    CodeSetVersionBean b = new CodeSetVersionBean();
                    b.setCodeset_version(p.getProject_name());
                    bean.add(b);
                }
            }
        }
    }
}
